<?php

namespace App;

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of Bootstrap
 *
 * @author Admin
 */
class Bootstrap extends \Core\Bootstrap
{	
	/**
	 * @var \DbSimple_Connect
	 */
	protected $_db;
	
	/**
	 *
	 * @var \Libs\Firephp\FirePHP 
	 */
	protected $_profiler;


	protected function _initTimezone()
	{
		date_default_timezone_set(\App::configs()->timezone);
		
		\Core\Session::start();
	}
	
	protected function _initRouters()
	{
		require_once \App::configs()->routers['path'];
		
		\Core\Routers::getInstance()->configs(\App::configs()->routers);
//		\Core\Routers::getInstance()->setAllowLangs(\App::configs()->langs['locales']);
		\Core\Routers::getInstance()->process($routers);
	}
	
	protected function _initProfiler()
	{
		 $this->_profiler = \Libs\Firephp\FirePHP::getInstance(true);
		 $this->_profiler->fb("hello world! i'm warning you!", \Libs\Firephp\FirePHP::WARN);
	}

	protected function _initDb()
	{
		require_once APPLICATION_PATH .'/libs/dbsimple/config.php';
		//require_once APPLICATION_PATH .'/libs/dbsimple/Generic.php';
		require_once APPLICATION_PATH .'/libs/dbsimple/Connect.php';
		
		$dbConfigs = \App::configs()->db;
		$dsn =	$dbConfigs['driver'] .'://'. 
						$dbConfigs['user'] .':'. $dbConfigs['password'] .'@'. 
						$dbConfigs['host'] .'/'. $dbConfigs['db'] .'?charset='. $dbConfigs['charset'];
		
		$this->_db = new \DbSimple_Connect($dsn);
		
		//$this->_db->setLogger('\App\Bootstrap::queryLogger');
		$this->_db->setErrorHandler('\App\Bootstrap::errorHandler');

		\App::db($this->_db);
		
		//$res = $this->_db->select('SELECT * FROM user');
		//print_r($res);
	}
	
	protected function _initLangs()
	{
		$lang = \App::routers()->getLang();
		
		// Set browser lang
		if(!$lang)
			$lang = \Core\Langs::getBrowserLang();
		
		// Set default lang
		if(!$lang || !isset(\App::configs()->langs['locales'][$lang]))
			$lang = \App::configs()->langs['default'];

		\Core\Langs::setLang($lang);
	}
	
	protected function _initLayout()
	{
		//require_once APPLICATION_PATH .'/libs/smarty/Smarty.class.php';
		
		//\App::layout(new \Smarty);
		\App::layout(new \Core\Layout(\App::configs()->layouts));
	}
	
	
	public static function queryLogger(&$DB, $query)
	{
		if (preg_match('/^\s*--\s+(\d|error)/', $query)) return;
		print("Query::".$query);
	}

	public static function errorHandler($msg, $error)
	{
		if (!error_reporting()) return;
		$dir = dirname(__FILE__). '/';
		$rpath = str_replace($dir, '', $error['context']);
		print($error['message']);
		print($rpath);
	}
	
}
